package com.taotao.order.interceptor;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CookieUtils;
import com.taotao.sso.service.UserLoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserLoginService userLoginService;
    @Value("${TT_TOKEN_KEY}")
    private String TT_TOKEN_KEY;
    @Value("${TT_LOGIN_URL}")
    private String TT_LOGIN_URL;

    //在进入controller方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = CookieUtils.getCookieValue(httpServletRequest, TT_TOKEN_KEY);
        String url = httpServletRequest.getRequestURL().toString();
        if (StringUtils.isEmpty(token)) {
            httpServletResponse.sendRedirect(TT_LOGIN_URL+"?redirect="+url);
            return false;
        }
        TaotaoResult result = userLoginService.getUserByToken(token);
        if (result.getStatus() != 200) {
            httpServletResponse.sendRedirect(TT_LOGIN_URL+"?redirect="+url);
            return false;
        }
        //程序走到这里,说明用户已登录,把用户信息设置到request中
        httpServletRequest.setAttribute("USER_INFO", result.getData());
        return true;
    }

    //在controller方法执行之后,返回ModelAndView之前执行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //在返回ModelAndView之后,页面渲染之前执行
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
